//
//  CZComposeViewController.swift
//  CZVVeiBo
//
//  Created by smile on 2017/8/5.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit

class CZComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.white
        setupNav()
        view.addSubview(textView)
        view.addSubview(bottomView)
        textView.addSubview(pictureView)
        
        textView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        bottomView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(40)
        }
        
        pictureView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: CZSCREENW - 20, height: CZSCREENW - 20))
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
        }
        
        // 监听按钮点击
        bottomView.closure = {[weak self](type)->() in
            
            switch type {
            case .picture:
                print("图片")
                self?.selectImage()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("笑脸")
                self?.switchKeyboard()
            case .add:
                print("+")
            }
            
        }
        
        // 监听配图中加号cell闭包回调
        pictureView.closure = {[weak self] in
            self?.selectImage()
        }
        
        // 注册系统通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        // 注册监听表情键盘按钮点击通知
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonbuttonClickNoti), name: CZEMOTICONBUTTONSNOTI, object: nil)
        // 注册监听表情键盘中删除按钮点击通知
        NotificationCenter.default.addObserver(self, selector: #selector(deletebuttonClickNoti), name: CZEMOTICONDELETEBUTTONNOTI, object: nil)
        
    }
    
    // MARK: - 设置导航
    private func setupNav(){
        // 
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: #selector(cancelClick))
        // 
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", imgName: nil, target: self, action: #selector(sendClick))
        // 设置右侧按钮不能点击
        navigationItem.rightBarButtonItem?.isEnabled = false
        // 
        navigationItem.titleView = titleView
    }
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        // 用户昵称
        let name = CZOAuthViewModel.share.userAccountModel?.screen_name ?? ""
        // 构造显示的文字
        let str = "发微博\n\(name)"
        // 范围
        let range = (str as NSString).range(of: name)
        // 通过字符串得到富文本
        let attr = NSMutableAttributedString(string: str)
        // 设置富文本的属性
        attr.addAttributes([NSForegroundColorAttributeName: CZAPPThemeColor, NSFontAttributeName: UIFont.systemFont(ofSize: 12)], range: range)
        // 创建label
        let lab = UILabel()
        // 对齐
        lab.textAlignment = .center
        // 换行
        lab.numberOfLines = 0
//        lab.text = str
        lab.attributedText = attr
        lab.sizeToFit()
        return lab
    }()
    // 自定义textView
    fileprivate lazy var textView: CZTextView = {
        let view = CZTextView()
        view.delegate = self
        view.font = UIFont.systemFont(ofSize: 16)
        view.placeholder = "请输入你想输入的文字内容"
        // 设置textView可以上下滚动
        view.alwaysBounceVertical = true
        return view
    }()
    // 底部视图
    fileprivate lazy var bottomView: CZComposeBottomView = CZComposeBottomView()
    // 自定义配图
    fileprivate lazy var pictureView: CZComposePictureView = CZComposePictureView()
    // 自定义表情键盘
    fileprivate lazy var keyboardView: CZEmoticonKeyboardView = CZEmoticonKeyboardView()
}
// MARK: - 底部视图中按钮点击事件处理
extension CZComposeViewController{
    // 选择图片
    fileprivate func selectImage(){
        
        let pickerVc = UIImagePickerController()
        // 设置代理
        pickerVc.delegate = self
        // 通过模态方式打开相册
        self.present(pickerVc, animated: true, completion: nil)
    }
    
    // 切换键盘
    fileprivate func switchKeyboard(){
        // 系统键盘
        if textView.inputView == nil {
            // 切换成表情键盘
            textView.inputView = keyboardView
        }else{
            // 表情键盘
            // 切换成系统键盘
            textView.inputView = nil
        }
        // 刷新
        textView.reloadInputViews()
        // 开启键盘第一响应者
        textView.becomeFirstResponder()
        
        // 判断是否是系统键盘和表情键盘
        bottomView.isEmoticon = (textView.inputView != nil)
    }
}

// MARK: - UIImagePickerControllerDelegate
extension CZComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    // 通过协议方法得到用户选择的图片音频视频
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        // 获取图片
        guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else{
            return
        }
        // 保存到配图中
        pictureView.addImage(image: image)
        // 关闭控制器
        picker.dismiss(animated: true, completion: nil)
    }
}

// MARK: - UITextViewDelegate
extension CZComposeViewController: UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
       
    }
    // 监听textView滚动
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 取消键盘第一响应者
        self.textView.resignFirstResponder()
    }
}

// MARK: - 监听事件
extension CZComposeViewController{
    @objc fileprivate func cancelClick(){
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func sendClick(){
        print("发送")
    }
}
// MARK: - 监听通知事件
extension CZComposeViewController{
    @objc fileprivate func keyboardWillChangeFrame(noti: Notification){

        // 判断userInfo是否为nil
        guard let userInfo = noti.userInfo else{
            return
        }
        // 通过UIKeyboardFrameEndUserInfoKey
        let rect = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        // 获取动画时长
        let duration = (userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        // 更新底部视图的底部约束
        bottomView.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(rect.origin.y - CZSCREENH)
        }
        // 设置动画
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    @objc fileprivate func emoticonbuttonClickNoti(noti: Notification){
        // 判断object是否为nil  而且是否可以转成一个模型
        guard let emoticonModel = noti.object as? CZEmoticonModel else {
            return
        }
        
        // 判断如果是emoji表情
        if emoticonModel.isEmoji {
            let code = emoticonModel.code ?? ""
            let codeStr = (code as NSString).emoji()
            // 设置给textView
            textView.insertText(codeStr ?? "")
        }else{
            // 图片表情
            // 记录原有的富文本
            let allAttr = NSMutableAttributedString(attributedString: textView.attributedText)
            // 获取全路径
            let allPathPng = emoticonModel.allPathPng ?? ""
            let image = UIImage(named: allPathPng, in: CZEmoticonTools.share.emoticonBundle, compatibleWith: nil)
            // 计算行高
            let lineHeight = UIFont.systemFont(ofSize: 16).lineHeight
            // 定义一个文本附件
            let att = NSTextAttachment()
            // 设置image
            att.image = image
            // 
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            // 定义一个不可变的富文本
            let attr = NSAttributedString(attachment: att)
//            // 拼接
//            allAttr.append(attr)
            // 获取光标微博
            let selectRange = textView.selectedRange
            // 插入
//            allAttr.insert(attr, at: selectRange.location)
            allAttr.replaceCharacters(in: selectRange, with: attr)
            // 设置富文本的属性font
            allAttr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 16)], range: NSRange(location: 0, length: allAttr.length))
            textView.attributedText = allAttr
            // 重新设置光标微博
            textView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            
            // 需要帮助系统发送通知
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            // 需要帮助系统使用代理执行协议方法
            textView.delegate?.textViewDidChange!(textView)
        }
    }
    
    // 删除按钮
    @objc fileprivate func deletebuttonClickNoti(){
        textView.deleteBackward()
    }
}
